package com.innazis.jfrogsurvey.backendmanager.task;

import android.content.Context;
import android.os.AsyncTask;

import com.innazis.jfrogsurvey.backendmanager.BackendManager;
import com.innazis.jfrogsurvey.config.Constants;
import com.innazis.jfrogsurvey.managers.SurveyManager;
import com.innazis.jfrogsurvey.obj.ServerResponse;
import com.innazis.jfrogsurvey.obj.SurveyObj;

import java.util.ArrayList;

/**
 * Created by Inna on 07.06.14.
 */
public class UpdateSurveysTask extends AsyncTask<Void, Void, Integer> {

    private Context mContext;

    public UpdateSurveysTask(Context context) {
        mContext = context;
    }

    @Override
    protected Integer doInBackground(Void... params) {
        ServerResponse response  =  new ServerResponse(Constants.FAILED, "");
        ArrayList<SurveyObj> lstSurveys = new ArrayList<SurveyObj>();
        BackendManager bManager = new BackendManager();
        try {
            lstSurveys = bManager.updateSurveys();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String messages = "";
        if (lstSurveys.size() != 0) {
            SurveyManager sManager = new SurveyManager(mContext);
            sManager.deleteAllSurveys();
            for (SurveyObj item : lstSurveys){
                messages += sManager.addSurvey(item);
            }
            response.set_message(messages);
            response.set_return_code(Constants.SUCCESS);
            bManager.sendReport(response);
        }
        return response.get_return_code();
    }
}
